import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config} from '../../shared/smartadmin.config';

declare var $: any;
declare var echarts: any;
declare var Viewer: any;
@Component({
	selector: 'sa-record',
	templateUrl: './record.component.html',
	styleUrls: ['./record.css']
})
export class RecordComponent implements OnInit {
	tableData:any= []; //table数据
	dataSource:string = ''
	pageOffset:number = 0;
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize :number= 10; //内置的分页每页条数
	searchKey:string = ''; //搜索keyword
	btnData:any = []; //权限按钮
	deviceAdd:boolean = false; //添加权限
	deviceEdit:boolean = false; //编辑权限
	deviceDelete:boolean = false; //删除权限
	deviceAudit:boolean = false; //审核权限
	rowId:string = '';//row数据的id	
	auditStatus:string = '';//审核状态
	remark:string = '';//审核意见
	userList:any; //用户数据
	userId:string = ''; //用户名称
	userName:string = ''; //用户ID
	startTime:string=''; //开始时间
	endTime:string=''; //结束时间
	selectedCompanyId:string = ''; //公司ID
	selectedCompanyName:string = ''; //公司名称
	imgPath:string = '';//图片
	carNumber:string = '';
	totalNum:number = 0;//echart-bar总数据统计
	constructor(private jsonApiService: JsonApiService, private router: Router,private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage == undefined? 1:queryParams.nowPage;
		});
	}

	ngOnInit() {
		this.initAllUser().then(()=>{
			this.selectUserName();
			this.load();
		});
		this.pageOffset = this.curPage-1;
		this.initBtn();
		this.initDate();	
		
		System.import('assets/js/viewer/viewer.js').then(
            () => {
                System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
                    () => {
                        System.import('assets/js/viewer/viewer.css').then(() => {})
                    })
            })
	}
	ngOnDestroy(){
		document.onclick = null;
	}
	//关闭bar 
	barClose(val){
		val.hide();
	}
	//打开bar弹窗
	dataShow(val,day){
		val.show();
		this.initChartBar(day);
	}
	initChartBar(day){
		this.totalNum = 0;
		let reqdata = "countForDay="+day,barX:any[] = [],barY:any[] = [];
		var chart = echarts.init(document.getElementById("chart_bar"));
		var option = {
			title:{
				text:'设备安装记录 - 共[' + this.totalNum+']台'
			},
		    color:['#1A6DDD'],
		    tooltip:{
		        trigger:'axis',
		        axisPointer:{
		            type:'line'
		        }
		    },
		    grid:{
		        left:'3%',
		        right:'4%',
		        bottom:'3%',
		        containLabel: true
		    },
		    xAxis:[{
	            type:'category',
	            data:barX,
	            axisTick: {
	                alignWithLabel: true
	            }
	       	}],
		    yAxis:[{
	            type:'value'
	       	}],
		    series:[{
	            name:'安装数量',
	            type:'bar',
	            barWidth: '50%',
	            data:barY
	       	}]
		};
		chart.setOption(option);
		this.jsonApiService.http("deviceInstall/statsForDay.html", reqdata).subscribe(data => {
			if(data.success){
				if(!data.data){this.jsonApiService.message('读取数据为空');return}
				var result = data.data;
				for(let item in result){
					this.totalNum += result[item];
					barX.push(item);
					barY.push(result[item]);
				}
				chart.setOption({
					title:{
						text:'设备安装记录 - 共[' + this.totalNum+']台'
					},
					xAxis:[{
			            data: barX
			       	}],
	                series:[{
	                    data: barY
	                }]
	            });
			}else{
				this.jsonApiService.message(data.message);
			}
		})
	}
	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						$("#datetimepicker1").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true,
						}).on("changeDate", function(e){
							var date = e.date;
							var time = common.getTimeMmss(date);
							$("#datetimepicker2").datetimepicker("setStartDate", time);
							that.startTime=time;
						});
						$("#datetimepicker2").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true,
						}).on("changeDate", function(e){
							var date = e.date;
							var time = common.getTimeMmss(date);
							$("#datetimepicker1").datetimepicker("setEndDate", time);
							that.endTime=time;
						});
						//首次进来不穿时间
//						var date = new Date();
//						$("#datetimepicker2").val(common.getTimeMmss(date));//当前时间
//						date.setDate(date.getDate() - 7);//设置前一周
//						$("#datetimepicker1").val(common.getTimeMmss(date));
						resolve();
					});
				}
			);
		})

	}
	//清除所选时间
	del_date(){
		this.startTime='';
		this.endTime='';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	//新增安装记录
	new_record(){
		this.router.navigate(['/device-management/record/record-page'], {queryParams: {type:'new'}});
	}
	//编辑安装记录
	updata_record(row) {
		this.router.navigate(['/device-management/record/record-page'], {queryParams: {id: row.id,type: 'updata',nowPage:this.curPage}});
	}
	// 数据导出
	exportData(){
		const param = {			
			'userId':this.userId,		//用户名
			'startTime':this.startTime,		//开始时间
			'endTime':this.endTime,			//结束时间
			'searchKey':this.searchKey,		//搜索内容
			'companyId':this.selectedCompanyId,			//选择的公司ID
		}
		let timeCheck = common.correctTime(param)
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		common.exprotDataFile(param, 'param', config.BaseURL + 'device/exportDeviceInstallList.html')		
	}
	cancelAudit(val){
		val.hide();
	}
	auditSubmit(val){
		if(this.auditStatus == ''){
			this.jsonApiService.message("请先选择审核状态");
			return
		}
		let reqdata = "id="+this.rowId+"&auditStatus="+this.auditStatus + "&remark=" + this.remark;
		this.jsonApiService.http("deviceInstall/auditDeviceInstall.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			this.load();
			val.hide();
		})
	}
	//审核状态改变
	auditStatusChange(val){
		this.auditStatus = val;
	}
	//安装记录审核
	audit_Record(row,val){
		this.rowId = row.id;
		this.remark = '';
		this.auditStatus = '';
		val.show();
	}
	//初始化权限按钮
	initBtn(){
		this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_deviceInstallation:recordManagement')));
		if(!this.btnData){return};
		for(let item of this.btnData){
			if(item.sourceKey === "deviceInstall:add"&&item.parentId){
				this.deviceAdd = true;
			}
			if(item.sourceKey === "deviceInstall:edit"&&item.parentId){
				this.deviceEdit = true;
			}
			if(item.sourceKey === "deviceInstall:del"&&item.parentId){
				this.deviceDelete = true;
			}
			if(item.sourceKey === "deviceInstall:audit"&&item.parentId){
				this.deviceAudit = true;
			}
		}
	}
	//表格搜索
	table_search() {
		this.curPage=1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//刷新
	refresh(){
    	this.load();
    }
	//擦除用户所选值
	delUserName(){
		this.userName = '';
		this.userId = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect2').val("");
		$("#select2-userNameSelect2-container").empty();
		$("#select2-userNameSelect2-container").attr("title","");
		$("#select2-userNameSelect2-container").prepend(str);
		this.load();
	}
	//初始化select2 选项
	selectUserName(){
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				$("#userNameSelect2").select2({
			    	language : "zh-CN",
			    	placeholder :"请选择",
			    	allowClear : true,
			    	data : this.userList,//为Select添加数据
			        templateResult: this.formatRepo
			    }).on ("select2:select", function (e){
		        	  	var data = e.params.data;
		        	  	that.userName = data.text;
		        	  	that.userId = data.id;
		        });
			})
		})
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//拉取
	initAllUser(){
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("deviceInstall/getUserFindList.html",null).subscribe(data=> {
				if(data.success){
					var userList = data.data;
		        	var selectdata = [];
		        	for(var i = 0 ; i < userList.length ; i++) {
		        		var obj = {
		        			id:userList[i].id,
		        			text:userList[i].name,
		        		}
		        		selectdata[i] = obj;
		        	}
				}
				that.userList = selectdata;
				resolve();
			})
		})
	}
	//初始化加载list数据
	load() {
		this.startTime =$('#datetimepicker1').val();
		this.endTime=$('#datetimepicker2').val();
		if(this.startTime==''&&this.endTime!==''){
			this.jsonApiService.message('起始时间不能为空');
			return;
		}
		if(this.startTime!==''&&this.endTime==''){
			this.jsonApiService.message('结束时间不能为空')
			return;
		}
		if(this.startTime!==''&& !common.checkDateFormat(this.startTime)){
			this.jsonApiService.message('起始时间格式错误')
			return;
		}
		if(this.endTime!==''&& !common.checkDateFormat(this.endTime)){
			this.jsonApiService.message('结束时间格式错误')
			return;
		}
		
		let reqdata = 'gridPager={"pageSize":' + this.pageSize +',"nowPage":' + this.curPage + ',"parameters":{"searchKey":"' + this.searchKey +
			'",startTime:"'+ this.startTime +
			'",endTime:"' + this.endTime +
			'",companyId:"' + this.selectedCompanyId +
			'",userId:"'+ this.userId +
			'",dataSource:"'+ this.dataSource +
		'"}}'
		this.jsonApiService.http("deviceInstall/findDeviceInstallList.html", reqdata).subscribe(data => {
			var result = data.exhibitDatas;
			if(result && result.length){
				for(let row of result){
					row.passTimeForInstall = common.secondToDate(row.passTimeForInstall);
				}
			}
			this.tableData = result;
			this.totalCount = data.recordCount;
		})
	}
	///分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	//删除
	del_record(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("deviceInstall/delDeviceInstallById.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message)
				this.load();
			})
		})
	}
	//公司选中回调
	companySelected(data){
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
	}

	//关闭图片弹窗
	imgClose(val){
		this.carNumber = '';
		this.imgPath = '';
		val.hide();
	}
	imgInfo: any = []; //单个图片列表
    //查看照片
    open_img(row, val) {
        var that = this;
        this.imgInfo = [];

        if(this.isViewer && $(".viewer-container").length > 0) {
			this.viewer.destroy();
			$(".viewer-container").remove();
		}
		
        val.show();

        this.carNumber = row.carNumber;

        for(var b = 0; b < row.imageInfo.length; b++) {
            row.imageInfo[b].localImg = [];
            for(let c = 0; c < row.imageInfo[b].imageList.length; c++) {
                let localImg;
                if(row.imageInfo[b].imageList[c].indexOf('http') == -1) {
                    if(row.imageInfo[b].imageList[c][0]  ==  '/') {
                        localImg = config.BaseURL + row.imageInfo[b].imageList[c].substr(1);
                    } else {
                        localImg = config.BaseURL + row.imageInfo[b].imageList[c];
                    }
                } else {
                    localImg = row.imageInfo[b].imageList[c];
                }
                row.imageInfo[b].localImg.push(localImg);
            }
        }
        this.imgInfo = row.imageInfo
    }
	bigImg: any = '' // 放大的图片
	isViewer: boolean = false; //默认隐藏
    //图片放大
    bigimg(row) {
        // modal.show();
        this.bigImg = row
        if(this.isViewer && $(".viewer-container").length < 1) {
            System.import('assets/js/viewer/viewer.js').then(
                () => {
                    System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
                        () => {
                            System.import('assets/js/viewer/viewer.css').then(() => {
                                this.showImg();
                            })
                        })
                })
        } else {
            this.showImg();
        }

    }
    //显示图片组件
    viewer: any = '';
    showImg() {
        var that = this;
        var imgList = $(".imagesInfo")[0];
        this.viewer = new Viewer(imgList, {
            url: 'src',
            title: function(image) {
                return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')';
            },
        });
        that.isViewer = true
    }
}